/*
 * @Author: 袁三金
 * @Date: 2023-10-12 00:08:26
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-10-13 10:50:02
 * @Description: 路由鉴权（守卫）
 */
import router from './router'
import nprogress from 'nprogress'
import setting from './setting'
import 'nprogress/nprogress.css'
import pinia from './store'
import useUserStore from './store/modules/user'
nprogress.configure({ showSpinner: false })
const userStore = useUserStore(pinia)
const username = userStore.username
router.beforeEach(async (to: any, from: any, next: any) => {
  document.title = `${setting.title}-${to.meta.title}`
  nprogress.start()
  const token = userStore.token
  //获取用户token判断是否登录成功
  if (token) {
    // 登录成功,访问login
    if (to.path == '/login') {
      next({ path: '/home' })
    }
    // 登录成功，访问其他六个路由
    else {
      // 是否有用户名，有的话直接放行
      if (username) {
        next()
      } else {
        // 没有用户名，先获取用户名
        try {
          await userStore.userInfo()
          // 放行
          next()
        } catch (error) {
          /**
           * token过期：获取不到用户信息了
           * token倍手动更改无法获取用户信息
           * 退出登录->用户相关数据清空
           */
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    // 用户未登录判断
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})
router.afterEach((to: any, from: any) => {
  nprogress.done()
})
